<template>
  <div class="pr-3 mt-3">
    <div class="app-h-center" style="color: red">
      <img :src="require('@/assets/icon.png')" alt="">
    </div>
    <div class="app-h-center pb-6 app-font-14 font-weight-bold" style="color: #999;margin-top: -12px;">
      场地费用:20元/小时
    </div>
    <el-form
      ref="appointmentForm"
      :model="appointmentInfo"
      :rules="rules"
      label-width="80px"
      lable-position="top"
      class="app-flex-1"
    >
      <el-form-item label="预约人" prop="name">
        <el-input
          v-model="appointmentInfo.name"
          placeholder="请输入预约人"
        />
      </el-form-item>
      <el-form-item label="手机" prop="mobile">
        <el-input
          v-model="appointmentInfo.mobile"
          placeholder="请输入预约人的手机号码"
        />
      </el-form-item>
      <el-form-item label="预约场地" prop="fieldId">
        <el-select
          v-model="appointmentInfo.fieldId"
          placeholder="请选择预约场地"
        >
          <el-option
            v-for="place in palceList"
            :key="place.id"
            :label="place.name"
            :value="place.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="预约日期" prop="beginDate">
        <el-date-picker
          v-model="appointmentInfo.beginDate"
          type="date"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          :picker-options="{
            disabledDate(time) {
              return time.getTime() < Date.now()
            },
          }"
          placeholder="选择预约日期"
        />
      </el-form-item>
      <el-form-item label="开始时间" prop="time">
        <el-time-select
          v-model="appointmentInfo.time"
          format="HH:mm:ss"
          value-format="HH:mm:ss"
          :picker-options="{
            start: '09:00',
            step: '01:00',
            end: '19:00'
          }"
          placeholder="选择预约开始时间"
          @change="generateLongTimeList"
        />
      </el-form-item>
      <el-form-item label="预约时长" prop="longTime">
        <el-select
          v-model="appointmentInfo.longTime"
          :disabled="!appointmentInfo.time"
          placeholder="请选择预约时长"
        >
          <el-option
            v-for="time,index in longTimeList"
            :key="index"
            :label="time.label"
            :value="time.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="兑换码" prop="sdk">
        <el-input
          v-model="appointmentInfo.sdk"
          placeholder="如果有，请输入优惠兑换码"
          @blur="getKyeDetail"
        />
      </el-form-item>
      <div class="app-hv-center app-h-64px font-weight-bold" style="color: red;">
        合计：{{ totalPrice > 0 ? totalPrice : 0 }}元(已优惠：{{ sdkValue }}元)
      </div>
    </el-form>
    <el-row class="mt-4" type="flex" align="center" justify="center">
      <el-button class="app-width-50p" type="primary" @click="submitAppointmentInfo">{{
        totalPrice > 0 ? '去支付' : '立即预约'
      }}</el-button>
    </el-row>

    <el-row class="app-h-128px app-hv-center" style="color: #bbb;font-size: 12px">
      <!-- <p>场地预约须知:</p>
      <p>
        1、预约场地每小时 20元;
      </p>
      <p>
        2、若场地预约成功但因个人原因无法到场，请提前4小时联系场地管理员进行修改。
      </p> -->
      特殊日期闭店，请关注“萤火虫无人机”官方公众号获取最新通知！
    </el-row>
  </div>
</template>
<script>
import {
  getPlaceList,
  addAppointmentOrder,
  getKey
} from '@/api/user'
import { host } from '@/utils/request'
import { appId } from '@/utils'
import request from '@/utils/request'
const allLongTimeList = [{
  value: 1,
  label: '1小时'
},{
  value: 2,
  label: '2小时'
},{
  value: 3,
  label: '3小时'
},{
  value: 4,
  label: '4小时'
},{
  value: 5,
  label: '5小时'
},{
  value: 6,
  label: '6小时'
},{
  value: 7,
  label: '7小时'
},{
  value: 8,
  label: '8小时'
},{
  value: 9,
  label: '9小时'
},{
  value: 10,
  label: '10小时'
},{
  value: 11,
  label: '11小时'
}]

export default {
  name: 'UserAppointment',
  data: () => {
    const checkMobile = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('手机号不能为空'))
      }
      if (value.length !== 11) {
        callback(new Error('请输入11位手机号'))
      } else {
        callback()
      }
    }
    return {
      host,
      appointmentInfo: {
        sdk: '',
        beginDate: '',
        time: '',
        beginTime: '',
        fieldId: null,
        longTime: null,
        mobile: '',
        name: ''
      },
      rules: {
        name: [{ required: true, message: '请输入预约人', trigger: 'change' }],
        time: [{ required: true, trigger: 'change' }],
        beginDate: [{ required: true, trigger: 'change' }],
        fieldId: [{ required: true, message: '请选择预约场地', trigger: 'change' }],
        longTime: [{ required: true, message: '请选择预约时长', trigger: 'change' }],
        mobile: [{ validator: checkMobile, required: true ,trigger: 'change' }]
      },
      sdkValue: 0,
      palceList: [],
      longTimeList: allLongTimeList
    }
  },
  computed: {
    totalPrice() {
      return (this.appointmentInfo.longTime * 20 - this.sdkValue).toFixed(2)
    }
  },
  mounted() {
    if (this.$route.query.token) {
      request.defaults.headers.common['token'] = this.$route.query.token
    } else {
      location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${encodeURIComponent(host + '/user/oauth')}&response_type=code&scope=snsapi_userinfo&state=1&connect_redirect=1#wechat_redirect`
    }
    // 场地用于选取
    getPlaceList({
      pageNo: 1,
      pageSize: 999
    }).then((res) => {
      if (res.code === 200) {
        this.palceList = res.data.dataList
      }
    })
  },
  methods: {
    submitAppointmentInfo() {
      this.$refs.appointmentForm.validate((valid) => {
        if (valid) {
          this.$confirm(`确认提交预约信息？`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            center: true
          }).then(() => {
            this.appointmentInfo.beginTime = this.appointmentInfo.beginDate + 'T' + this.appointmentInfo.time + ':00'
            const params = { ...this.appointmentInfo }
            delete params.time
            delete params.beginDate
            addAppointmentOrder(params).then((res) => {
              if (res.code === 200) {
                if (res.data.msg === '预约成功') {
                  this.$router.replace({ name: 'success' })
                  return
                }
                const { appid, nonceStr, paySign, timeStamp, prepay_id,signType } = res.data.data
                if (!(typeof WeixinJSBridge === 'undefined')) {
                  // 调起支付
                  // eslint-disable-next-line no-undef
                  WeixinJSBridge.invoke('getBrandWCPayRequest', {
                    appId: appid, // 公众号ID，由商户传入
                    timeStamp, // 时间戳，自1970年以来的秒数
                    nonceStr, // 随机串
                    package: `prepay_id=${prepay_id}`,
                    signType, // 微信签名方式：
                    paySign // 微信签名
                  },
                  res => {
                    if (res.err_msg === 'get_brand_wcpay_request:ok') {
                      // 使用以上方式判断前端返回,微信团队郑重提示：
                      // res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
                      this.$router.replace({ name: 'success' })
                    }
                  })
                } else {
                  this.$message.error('当前环境不支持微信支付，请前往微信客户端进行预约')
                }
              }
            })
          }).catch(() => {
          })
        } else {
          this.$message.error('请填写完整信息')
        }
      })
    },
    getKyeDetail() {
      if (this.appointmentInfo.sdk.length === 32) {
        getKey({
          sdk: this.appointmentInfo.sdk
        }).then((res) => {
          if (res.code === 200) {
            if (res.data.type === 1) {
              this.$message.error('兑换码已使用')
            } else {
              this.sdkValue = res.data.price
            }
          }
        })
      } else if (this.appointmentInfo.sdk) {
        this.$message.error('请输入正确的兑换码')
      }
    },
    generateLongTimeList() {
      this.longTimeList = allLongTimeList.slice(0,20 - parseInt(this.appointmentInfo.time))
    }
  }
}
</script>
<style lang="scss">
.el-message-box {
  width: 360px;
}
</style>
